package SEG_ApplicationLayer;

import CommonApplicationLayer.InfoComun;
import CommonApplicationLayer.MetodoComun;
import CommonApplicationLayer.SMSComun;
import SEG_BusinessLayer.SEG_AccesoBL;
import SEG_EntityLayer.SEG_AccesoEL;
import SEG_EntityLayer.SEG_MenuEL;
import SEG_EntityLayer.SEG_OpcionEL;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.Timer;

public class FrmSEG_Principal extends JFrame {

    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Variables">

        private final static FrmSEG_Principal _instancia = new FrmSEG_Principal();
        private byte sysEmpresa;
        private short sysUsuario;
        private String sysLogin;
        private String sysNombres;
        private ActionListener accion = new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                cargarMostrarFrame(e);
                            }
                        };

    // </editor-fold>
    
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Seguridad">

        private void obtenerDatosSesion() {
            sysEmpresa = InfoComun.getInstancia().getIdEmpresa();
            sysUsuario = InfoComun.getInstancia().getIdUsuario();
            sysLogin = InfoComun.getInstancia().getLogin();
            sysNombres = InfoComun.getInstancia().getNombres();
        }

    // </editor-fold>

    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Apariencia">

    // </editor-fold>    
    
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="ControlEventos">
    
    private FrmSEG_Principal() {
        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource("/Resources/world.png")).getImage());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        lblLogin = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButton3 = new javax.swing.JButton();
        lblNombre = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jButton5 = new javax.swing.JButton();
        lblEquipo = new javax.swing.JButton();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jToolBar2 = new javax.swing.JToolBar();
        jButton7 = new javax.swing.JButton();
        lblFecha = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        jButton9 = new javax.swing.JButton();
        lblHora = new javax.swing.JButton();
        jToolBar3 = new javax.swing.JToolBar();
        btnSalir = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton1.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/user_suit.png"))); // NOI18N
        jButton1.setText("Usuario:");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jToolBar1.add(jButton1);

        lblLogin.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        lblLogin.setText("lblLogin");
        lblLogin.setFocusable(false);
        lblLogin.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblLogin.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(lblLogin);
        jToolBar1.add(jSeparator1);

        jButton3.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/vcard.png"))); // NOI18N
        jButton3.setText("Nombres:");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jToolBar1.add(jButton3);

        lblNombre.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        lblNombre.setText("lblNombre");
        lblNombre.setFocusable(false);
        lblNombre.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblNombre.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(lblNombre);
        jToolBar1.add(jSeparator2);

        jButton5.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/monitor.png"))); // NOI18N
        jButton5.setText("Equipo:");
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jToolBar1.add(jButton5);

        lblEquipo.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        lblEquipo.setText("lblEquipo");
        lblEquipo.setFocusable(false);
        lblEquipo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToolBar1.add(lblEquipo);

        jDesktopPane1.setBackground(new java.awt.Color(153, 153, 153));
        jDesktopPane1.setAutoscrolls(true);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        jButton7.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/date.png"))); // NOI18N
        jButton7.setText("Fecha:");
        jButton7.setFocusable(false);
        jButton7.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jToolBar2.add(jButton7);

        lblFecha.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        lblFecha.setText("lblFecha");
        lblFecha.setFocusable(false);
        lblFecha.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblFecha.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(lblFecha);
        jToolBar2.add(jSeparator4);

        jButton9.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/clock.png"))); // NOI18N
        jButton9.setText("Hora:");
        jButton9.setFocusable(false);
        jButton9.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jToolBar2.add(jButton9);

        lblHora.setFont(new java.awt.Font("Lucida Fax", 0, 10)); // NOI18N
        lblHora.setText("lblHora");
        lblHora.setFocusable(false);
        lblHora.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblHora.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(lblHora);

        jToolBar3.setFloatable(false);
        jToolBar3.setRollover(true);

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/power.png"))); // NOI18N
        btnSalir.setFocusable(false);
        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });
        jToolBar3.add(btnSalir);
        jToolBar3.add(jSeparator3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jToolBar3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

        private void cargarMostrarFrame(ActionEvent evt){
            SEG_OpcionEL opcion;
            ImageIcon icono;
            try {
                try {
                    opcion = (SEG_OpcionEL) ((JMenuItem)evt.getSource()).getClientProperty("tag");
                } catch(ClassCastException ex) {
                    opcion = (SEG_OpcionEL) ((JButton)evt.getSource()).getClientProperty("tag");
                }
                if ( this.getClass().getResource("/Resources/"+opcion.getIcono())!=null ) {
                    icono = new ImageIcon(this.getClass().getResource("/Resources/"+opcion.getIcono()));
                }
                else {
                    icono = new ImageIcon(this.getClass().getResource("/Resources/application.png"));
                }
                Class clase = Class.forName(opcion.getPaquete()+"."+opcion.getFormulario());
                
                for ( JInternalFrame f : jDesktopPane1.getAllFrames() )
                {
                    if ( f.getClass().equals(clase) )
                    {
                        f.setIcon(false);
                        f.setVisible(true);
                        f.moveToFront();
                        return;
                    }
                }
                JInternalFrame f;
                f = (JInternalFrame)clase.newInstance( );
                f.putClientProperty("tag", opcion);
                f.setFrameIcon((Icon) icono);
                f.setTitle(opcion.getNombre());
                centerJIF(f);
                jDesktopPane1.add(f);
                f.setVisible(true);
                f.moveToFront();
                
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            } catch (InstantiationException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            } catch (PropertyVetoException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            } catch (IllegalAccessException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
    
    //</editor-fold>

    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Funcionalidad">

        public static FrmSEG_Principal getInstancia() {
            return _instancia;
        }

        public void cargarModulo(byte modulo, String dModulo) {
            jDesktopPane1.removeAll();
            jMenuBar1.removeAll();
            jToolBar3.removeAll();
            jToolBar3.add(btnSalir);
            jToolBar3.add(jSeparator3);
            this.setTitle(SMSComun.smsEmpresa+" - "+ dModulo);
            obtenerDatosSesion();
            cargarDatosUsuario();
            cargarMenuUsuario(modulo);
        }

        private void cargarDatosUsuario() {
            try {
                InetAddress localMachine = InetAddress.getLocalHost();

                lblLogin.setText(MetodoComun.getInstancia().getNomPropio(sysLogin));
                lblNombre.setText(MetodoComun.getInstancia().getNomPropio(sysNombres));
                lblEquipo.setText(localMachine.getHostName());
                lblFecha.setText(MetodoComun.getInstancia().getFecha());

                Timer timer = new Timer (1000, new ActionListener () {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        lblHora.setText(MetodoComun.getInstancia().getHora());
                    }
                });
                timer.start();
            } catch (UnknownHostException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
        
        private void cargarOpcionUsuario(List<SEG_AccesoEL> lista, JMenu item, short menu, short padre)
        {
            for ( SEG_AccesoEL acceso : lista ) {
                SEG_OpcionEL opcion = acceso.getOpcion();
                if ( opcion.getMenu().getMenu() == menu && opcion.getPadre().getOpcion()==padre ) {
                    ImageIcon icono = new ImageIcon(this.getClass().getResource("/Resources/application.png"));
                    if ( this.getClass().getResource("/Resources/"+opcion.getIcono())!=null ) {
                        icono = new ImageIcon(this.getClass().getResource("/Resources/"+opcion.getIcono()));
                    }
                    if ( opcion.isSeparador() ) {
                        item.add(new JSeparator());
                    }
                    if ( opcion.getTipo().equals("FRM") ) {
                        JMenuItem opc = new JMenuItem(opcion.getNombre(), icono);
                        opc.setEnabled(false);
                        if ( acceso.getAcceso() > 0 ) {
                            opc.putClientProperty("tag", opcion);
                            opc.setEnabled(true);
                            opc.addActionListener(accion);
                            if ( acceso.isAccesoDirecto() ) {
                                JButton button = new JButton("", icono);
                                button.putClientProperty("tag", opcion);
                                button.setToolTipText(opcion.getTooltip());
                                button.addActionListener(accion);
                                jToolBar3.add(button);
                            }
                        }
                        item.add(opc);
                    }
                    else {
                        JMenu subitem = new JMenu(opcion.getNombre());
                        cargarOpcionUsuario(lista, subitem, menu,opcion.getOpcion());
                        item.add(subitem);
                    }
                }
            }
        }
        
        public void centerJIF(JInternalFrame jif) {
            Dimension desktopSize = jDesktopPane1.getSize();
            Dimension jInternalFrameSize = jif.getSize();
            int width = (desktopSize.width - jInternalFrameSize.width) / 2;
            int height = (desktopSize.height - jInternalFrameSize.height) / 2;
            jif.setLocation(width, height);
            jif.setVisible(true);
        }

    //</editor-fold>
    
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="AccesoDatos">

        private void cargarMenuUsuario(byte modulo)
        {
            try {
                List<SEG_AccesoEL> lista = SEG_AccesoBL.getInstancia().ObtenerAccesoUsuario(sysEmpresa, modulo, sysUsuario);
                Set<SEG_MenuEL> menu = new TreeSet<SEG_MenuEL>(new Comparator(){
                    @Override
                    public int compare(Object o1, Object o2) {  
                        SEG_MenuEL e1 = (SEG_MenuEL) o1;  
                        SEG_MenuEL e2 = (SEG_MenuEL) o2;  
                        int codigo1 = e1.getOrden();  
                        int codigo2 = e2.getOrden();  
  
                        if (codigo1 > codigo2) {  
                            return 1;  
                        } else if (codigo1 < codigo2) {  
                            return -1;  
                        } else {  
                            return 0;  
                        } 
                    }  
                });
                
                for (SEG_AccesoEL acceso : lista)
                {
                    menu.add(acceso.getOpcion().getMenu());
                }
                for (SEG_MenuEL m : menu)
                {
                    JMenu item = new JMenu(m.getNombre());
                    cargarOpcionUsuario(lista, item, m.getMenu(),(short)0);
                    jMenuBar1.add(item);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), SMSComun.smsEmpresa, JOptionPane.ERROR_MESSAGE);
            }
        }
        
    // </editor-fold>
    
    //--------------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="Validacion">

    // </editor-fold>
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton9;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JToolBar jToolBar3;
    private javax.swing.JButton lblEquipo;
    private javax.swing.JButton lblFecha;
    private javax.swing.JButton lblHora;
    private javax.swing.JButton lblLogin;
    private javax.swing.JButton lblNombre;
    // End of variables declaration//GEN-END:variables
}
